import 'dart:async';
import 'dart:collection';

import 'package:card_swiper/card_swiper.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:hari_curly/src/common/style.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:hari_curly/src/states/device_info_state.dart';

import '../../../common/event.dart';
import '../../../common/utils.dart';
import '../../../model/device_model.dart';
import '../../../states/device_connect_status.dart';
const String serviceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";
const String charWriteUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";
const String charNotifyUUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";
class ConnectButton extends StatefulWidget {
  const ConnectButton({super.key});

  @override
  State<StatefulWidget> createState() => _ConnectButtonState();
}

class _ConnectButtonState extends State<ConnectButton> {
  late  BluetoothService _bluetoothService;
  Timer? _timer;
  Queue<int> _queue = Queue();
  bool _dealFlag = false;
  @override
  void initState() {
    super.initState();
    if (mounted) {
      _initData();
      eventBus.on<DeviceConnectStatusRefreshEvent>().listen((event) {
        setState(() {});
      });
    }
  }
  late BluetoothCharacteristic _writeCharacteristic;
  late BluetoothCharacteristic _notifyCharacteristic;



  void _initData() async {
    if (context.read<DeviceConnectStatus>().getDevice().status == "1") return;
    DeviceModel? deviceModel = await DeviceModel.getLastConnected();
    if (deviceModel != null) {
      DialogUtil.showLoadingDialog(context);
      BluetoothDevice device = BluetoothDevice.fromId(deviceModel.id!);
      device.connect(timeout: Duration(seconds: 5));
      device.connectionState.listen((BluetoothConnectionState state) async {
        if (state == BluetoothConnectionState.connected) {
          FlutterBluePlus.stopScan();
          Future.delayed(Duration(seconds: 1), () async {
            DialogUtil.hideLoadingDialog();
            await DeviceModel.connected(deviceModel.id!);
            context.read<DeviceConnectStatus>().connect(deviceModel);
            List<BluetoothService> services = await device.discoverServices();
            services.forEach((service) async {
              if(service.serviceUuid.toString() == serviceUUID){
                _bluetoothService = service;
                List<BluetoothCharacteristic> characteristics = service.characteristics;
                characteristics.forEach((characteristic)  async{
                  if(characteristic.characteristicUuid.toString() == charWriteUUID){
                    _writeCharacteristic = characteristic;
                    context.read<DeviceInfoStatus>().setWriteCharacteristic(_writeCharacteristic);
                    __initHeartBeat(_writeCharacteristic);
                  }
                  if(characteristic.characteristicUuid.toString() == charNotifyUUID){
                    _notifyCharacteristic = characteristic;
                    await _notifyCharacteristic.setNotifyValue(true);
                    _notifyCharacteristic.onValueReceived.listen((value) {
                      LogUtils.log("收到消息====>${value}");
                      _queue.add(value[0]);
                      if(_queue.length>3&&_dealFlag==false){
                        _dealFlag=true;
                        while(_queue.length>3) {
                         int first = _queue.removeFirst();
                         if(first==0xAA){
                          int next = _queue.removeFirst();
                          int last = _queue.removeFirst();
                          if(next==0x09){
                            // 0 0 0 0 0 0 0 0
                            // - high middle low - high middle low
                           if(BitUtils.getBitIsOne(last, 1)){
                              context.read<DeviceInfoStatus>().setTemperature("middle");
                            }else if(BitUtils.getBitIsOne(last, 2)){
                              context.read<DeviceInfoStatus>().setTemperature("high");
                            }else if(BitUtils.getBitIsOne(last, 3)){
                              context.read<DeviceInfoStatus>().setTemperature("higher");
                            }else  if(!BitUtils.getBitIsOne(last, 1)){
                             context.read<DeviceInfoStatus>().setTemperature("low");
                           }
                           if(BitUtils.getBitIsOne(last, 5)){
                              context.read<DeviceInfoStatus>().setWind("low");
                            }else if(BitUtils.getBitIsOne(last, 6)){
                              context.read<DeviceInfoStatus>().setWind("middle");
                            }else if(BitUtils.getBitIsOne(last, 7)){
                              print("high====>${last}");
                              context.read<DeviceInfoStatus>().setWind("high");
                            }
                            eventBus.fire(DeviceStatusRefresh());

                          }else if(next==0x07&&last==0x01){
                            eventBus.fire(DeviceAutoStartEvent());
                          }
                          next=-1;
                          last=-1;
                         }
                        }
                        _dealFlag=false;
                      }
                    });
                  }
                });

              }

            });
          });
        }else if (state == BluetoothConnectionState.disconnected&& context.read<DeviceConnectStatus>().state.status == "1") {
          context.read<DeviceConnectStatus>().disconnect();
          if(_timer!=null){
            _timer!.cancel();
          }
        }
      });
      Future.delayed(Duration(seconds: 5),(){
        DialogUtil.hideLoadingDialog();
      });
    }
  }
  __initHeartBeat(BluetoothCharacteristic characteristic){
    if(_timer!=null){
      _timer!.cancel();
    }
    _timer= Timer.periodic(Duration(seconds: 1), (timer) async {
      try {
        await characteristic.write([0xBB,0x09,0x01]);
      } catch (e) {
        context.read<DeviceConnectStatus>().disconnect();
        setState(() {
        });
      }
    });
  }
    //10 20 30
  @override
  Widget build(BuildContext context) {
    // 操作按钮
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      height: 60,
      child: Flex(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        direction: Axis.horizontal,
        children: [
          Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 12, horizontal: 5),
              child: ElevatedButton.icon(
                onPressed: () {
                  if (context.read<DeviceConnectStatus>().getDevice().status ==
                      "1")
                    return;
                  context.push("/device/scan");
                },
                icon: Icon(Icons.bluetooth),
                label: BlocBuilder<DeviceConnectStatus, DeviceModel>(
                  builder: (context, state) {
                    return Text(
                      state.status == '1'
                          ? 'bluetooth_status_connected'.tr()
                          : 'bluetooth_status'.tr(),
                    );
                  },
                ),
                style: customButtonStyle,
              ),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.symmetric(vertical: 12, horizontal: 5),
              child: ElevatedButton.icon(
                onPressed: () {},
                icon:  BlocBuilder<DeviceConnectStatus, DeviceModel>(
                  builder: (context, state) {
                    if (state.status == '1') {
                      return Icon(Icons.link);
                    }else{
                      return Icon(Icons.link_off);
                    }
                  },
                ),
                label: BlocBuilder<DeviceConnectStatus, DeviceModel>(
                  builder: (context, state) {
                    return Text(
                      state.status == '1'
                          ? 'device_status_normal'.tr()
                          : 'device_status_abnormal'.tr(),
                    );
                  },
                ),
                style: customButtonStyle,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

final customButtonStyle = ButtonStyle(
  foregroundColor: WidgetStateProperty.all(Colors.white),
  backgroundColor: WidgetStateProperty.all(unitBgColor),
);
